
var graph = new joint.dia.Graph;
//自定义link
joint.dia.Link.define('standard.Link', {
    router: {
        name: 'normal'
    },
    labels: [],
    smooth: true,
    attrs: {
        line: {
            stroke: '#20C1DD',
            strokeDasharray: '0',
            strokeWidth: 2,
            fill: 'none',
            sourceMarker: {
                type: 'path',
                d: 'M 0 0 0 0',
                stroke: 'none'
            },
            targetMarker: {
                type: 'path',
                d: 'M 0 -5 -10 0 0 5 z',
                stroke: 'none'
            }
        }
    }
}, {

    getMarkerWidth: function(type) {
        var d = (type === 'source') ? this.attr('line/sourceMarker/d') : this.attr('line/targetMarker/d');
        return this.getDataWidth(d);
    },

    getDataWidth: _.memoize(function(d) {
        return (new g.Path(d)).bbox().width;
    })

}, {

    connectionPoint: function(line, view, magnet, opt, type, linkView) {
        var markerWidth = linkView.model.getMarkerWidth(type);
        opt = { offset: markerWidth, stroke: true };
        // connection point for UML shapes lies on the root group containg all the shapes components
        if (view.model.get('type').indexOf('uml') === 0) opt.selector = 'root';
        return joint.connectionPoints.boundary.call(this, line, view, magnet, opt, type, linkView);
    }
});
var paper = new joint.dia.Paper({
    width: 2000,
    height: 1500,
    model: graph,
    gridSize: 1,
    snapLinks: true,
    linkPinning: false,
    defaultLink: new joint.shapes.standard.Link({
        // router: { name: 'manhattan' },
       // connector: { name: 'rounded' },
        smooth: true,
        attrs: {
            '.connection': {
                stroke: '#20C1DD',
                'stroke-width': 2,
                pointerEvents: 'none',
            },
            '.marker-target': {
                fill: '#20C1DD',
                stroke: '#fff',
                d: 'M 10 0 L 0 5 L 10 10 z'
            }
        },
    }),
    
   /* defaultLink:  new joint.shapes.standard.Link,*/
    defaultConnectionPoint: joint.shapes.standard.Link.connectionPoint
});
//paper背景
var bgimage = ''
paper.drawBackground({
    image : bgimage
});

//控制纸张
var paperScroller = new joint.ui.PaperScroller({
    paper: paper,
    autoResizePaper: true,
    padding: 50,
    cursor: 'grab'
});
// 移动纸张
paper.on('blank:pointerdown', paperScroller.startPanning);
$('#paper').append(paperScroller.render().el);
paperScroller.center();    //移动到页面的中间


var commandManager = new joint.dia.CommandManager({
    graph: graph
});
var toolbar = new joint.ui.Toolbar({   //头部控制模块
    groups: {
        'undo-redo': { index: 1 },
        'clear': { index: 2 },
        'export': { index: 3 },
        'print': { index: 4 },
        'layout': { index: 5 },
        'order': { index: 6 },
        'zoom': { index: 7 },
        'fullscreen': { index: 8 },
        'grid': { index: 9 },
        'snapline': { index: 10 }
    },
    tools: [
        {
            type: 'button',
            name: 'undo',
            group: 'undo-redo',
            attrs: {
                button: {
                    'id':'btn-undo',
                    'data-tooltip': '撤销',
                    'data-tooltip-position': 'top',
                    'data-tooltip-position-selector': '.toolbar-container'
                }
            }
        },
        {
            type: 'button',
            name: 'redo',
            group: 'undo-redo',
            attrs: {
                button: {
                    'id':'btn-redo',
                    'data-tooltip': '返回',
                    'data-tooltip-position': 'top',
                    'data-tooltip-position-selector': '.toolbar-container'
                }
            }
        },
        {
            type: 'button',
            name: 'clear',
            group: 'clear',
            attrs: {
                button: {
                    id: 'btn-clear',
                    'data-tooltip': '清除',
                    'data-tooltip-position': 'top',
                    'data-tooltip-position-selector': '.toolbar-container'
                }
            }
        },
      /*  {
            type: 'button',
            name: 'svg',
            group: 'export',
            text: 'Export SVG',
            attrs: {
                button: {
                    id: 'btn-svg',
                    'data-tooltip': '导出SVG',
                    'data-tooltip-position': 'top',
                    'data-tooltip-position-selector': '.toolbar-container'
                }
            }
        },
        {
            type: 'button',
            name: 'png',
            group: 'export',
            text: 'Export PNG',
            attrs: {
                button: {
                    id: 'btn-png',
                    'data-tooltip': '导出PNG',
                    'data-tooltip-position': 'top',
                    'data-tooltip-position-selector': '.toolbar-container'
                }
            }
        },*/
        {
            type: 'button',
            name: 'print',
            group: 'print',
            attrs: {
                button: {
                    id: 'btn-print',
                    'data-tooltip': '打印',
                    'data-tooltip-position': 'top',
                    'data-tooltip-position-selector': '.toolbar-container'
                }
            }
        },
        {
            type: 'button',
            group: 'layout',
            name: 'layout',
            attrs: {
                button: {
                    id: 'btn-layout',
                    'data-tooltip': '自动布局',
                    'data-tooltip-position': 'top',
                    'data-tooltip-position-selector': '.toolbar-container'
                }
            }
        },
        {
            type: 'zoom-to-fit',
            name: 'zoom-to-fit',
            group: 'zoom',
            attrs: {
                button: {
                    'data-tooltip': '自适应缩放',
                    'data-tooltip-position': 'top',
                    'data-tooltip-position-selector': '.toolbar-container'
                }
            }
        },
        {
            type: 'label',
            name: 'zoom-slider-label',
            group: 'zoom',
            text: 'Zoom:'
        },
        {
            type: 'zoom-slider',
            name: 'zoom-slider',
            group: 'zoom'
        },

     /*   {
            type: 'button',
            name: 'search',
            group: 'last',
            text: '导出json',
            class : 'abc',
            attrs: {
                button: {
                    id: 'JSON',
                    'data-tooltip': '添加流程',
                    'data-tooltip-position': 'top',
                    'data-tooltip-position-selector': '.toolbar-container'
                }
            }
        },
        {
            type: 'button',
            name: 'refresh',
            group: 'last',
            text: '刷新',
            attrs: {
                button: {
                    id: 'btn-refresh',
                    'data-tooltip': '刷新',
                    'data-tooltip-position': 'top',
                    'data-tooltip-position-selector': '.toolbar-container'
                }
            }
        },*/
        {
            type: 'button',
            name: 'save',
            group: 'last',
            text: '保存',
            attrs: {
                button: {
                    id: 'btn-save',
                    'data-tooltip': '保存',
                    'data-tooltip-position': 'top',
                    'data-tooltip-position-selector': '.toolbar-container'
                }
            }
        }
    ],
    references: {
        paperScroller: paperScroller,
        commandManager: commandManager
    }
});

//toolbar挂载到dom
$('#app').prepend(toolbar.render().el);


//模板开始
 var stencil = new joint.ui.Stencil({ graph: graph,paper: paper, width: 80,
        groups: {
            one: { label: '数据库', index: 1 },
           /* two: { label: 'Hadoop', index: 2,closed:true },
            three: { label: '通用', index: 3,closed:true }*/
        },
        dragEndClone: function(cell) {
            var clone = cell.clone();
            var type = clone.get('type');
     
            var originalSize = clone.get('size');
            clone.set('size', {
                width: originalSize.width * 1.6,
                height: originalSize.height * 1.6
            });

            return clone;
        }
    });
    $('#stencil-holder').append(stencil.render().el);

  var img1 = new joint.shapes.basic.Image({
    position: { x: 25, y: 15 },
    size: { width: 25, height: 25 },
    attrs: {
        image: { width: 25, height: 25, 'xlink:href': '/assets/custom/draw/img/saveProcess.png',class:'procedure'},
        text: {"ref-y": -5,text:'存储过程'},
    },
    description: 'image'
    	
});
  
  var imgArray = [];
  for(var i =0;i<4;i++){
	  var img2= new joint.shapes.basic.Image({
		    position: { x: 25, y: 15 + i*55 },
		    size: { width: 25, height: 25 },
		    attrs: {
		        image: { width: 25, height: 25},
		        text: {"ref-y": -5},
		    },
		    description: 'image'
		    	
		});
	  if(i === 0){
		  img2.attributes.attrs.image["xlink:href"] = '/assets/custom/draw/img/HIVE.svg';
		  img2.attributes.attrs.text.text = "HIVE查询";
	  }else if(i === 1){
		  img2.attributes.attrs.image["xlink:href"] = '/assets/custom/draw/img/SPARK.svg';
		  img2.attributes.attrs.text.text = "Spark程序";
	  }else if(i === 2){
		  img2.attributes.attrs.image["xlink:href"] = '/assets/custom/draw/img/map-reduce.svg';
		  img2.attributes.attrs.text.text = "MapReduce";
	  }else if(i === 3){
		  img2.attributes.attrs.image["xlink:href"] = '/assets/custom/draw/img/SH.svg';
		  img2.attributes.attrs.text.text = "Sh命令";
	  }
	  imgArray.push(img2);
  }
  
stencil.load({ one: [img1]});



//添加加入下拉框
$('div[data-group="last"]').prepend('<div class="addPullDown"><button class="joint-theme-default joint-widget addPBtn">加入 <span class="layui-icon">&#xe61a;</span></button><ul class="pullDown display_none"></ul></div>');

//页面初始化
var  base = $("#base").attr("ul");
//var  base = "http://192.168.0.130:8099";
var tuid= $('.tab-pane.active', window.parent.document).attr('data-tuid'); //任务单元id
//下拉框‘加入’的数据
$.ajax({
    url : base + '/rest/tuLayout/findTuLayoutType',
    type :'GET',
    dataType : 'JSON',
    data : {},
    success : function(result){
        console.log(result);
        $.each(result.data,function (i,v) {
            if(v.addUrl != null && v.addUrl != ''){
               var str =  '<li><a href="javascript:;" data-addUrl="/page/'+v.addUrl+'" name="'+v.stepTypeName+'" class="'+v.stepTypeCode+'">'+v.stepTypeName+'</a></li>';
                $('.pullDown').append(str)
            }
        })
    }
});
//页面元素初始化
var startId;
$.ajax({
    url : base+'/rest/tuLayout/selectGraphStepsAndLinks',
    type : 'GET',
    dataType: 'JSON',
    data :{tuId : tuid},
    success :function (result) {
        console.log(result);
        var arr = [];var position = 500;
      /*  if(result.object.stepList.length > 0){
            $.each(result.object.stepList,function(i,v){
                console.log(v);
                var imgTemp = {
                    "angle": 0,
                    "attrs" : {
                        "image": {"width": 40, "height": 40,'class':v.stepTypeCode,"stepId":v.stepId,'taskObjectId':v.taskObjectId},
                        "text": {text: v.name},
                    },
                    "id" : v.stepId,
                    "description": "image",
                    "position": {x: v.positionX?v.positionX:position+=200, y: v.positionY?v.positionY:600},
                    "size": {width: 40, height: 40},
                    "type": "basic.Image",
                    "z" : 1
                };
           //     imgTemp.attrs.image.href = (v.stepTypeCode == 'START')? ((v.stepTypeCode == 'DXFLOW')?"./img/DXFLOW.png":"./img/process_start.png"):"./img/TU.png";
                if (v.stepTypeCode === 'START'){
                    imgTemp.attrs.image.href = "/assets/custom/draw/img/process_start.png";
                    startId = v.stepId;
                }else if (v.stepTypeCode === 'DXFLOW'){
                    imgTemp.attrs.image.href = "/assets/custom/draw/img/DXFLOW.png"
                }else {
                    imgTemp.attrs.image.href = "/assets/custom/draw/img/TU.png"
                }
                arr.push(imgTemp)
            });

            $.each(result.object.linkList,function (i, v) {
                var linkObj = {
                    "type" : 'link',
                    "z": 2,
                    id : v.linkId,
                    source : {id : v.fromStepId},
                    target: {id : v.endStepId},
                 //   connector: { name: 'rounded' },
                    smooth: true,
                    attrs: {
                        '.connection': {
                            stroke: '#20C1DD',
                            'stroke-width': 1.5,
                            pointerEvents: 'none',
                        },
                        '.marker-target': {
                            fill: '#20C1DD',
                            stroke: '#fff',
                            d: 'M 10 0 L 0 5 L 10 10 z'
                        }
                    },
                };
                arr.push(linkObj)
            });

            graph.fromJSON(obj);
            paperScroller.centerContent();
        }*/
        if(result.object.stepList.length > 0){
        		
            $.each(result.object.stepList,function(i,v){
                var imageUrl;
                if (v.stepTypeCode === 'START'){
                    imageUrl = "/assets/custom/draw/img/process_start.png";
                    startId = v.stepId;
                }else if (v.stepTypeCode === 'DXFLOW'){
                    imageUrl = "/assets/custom/draw/img/DXFLOW.png"
                }else if(v.stepTypeCode === 'TU'){
                    imageUrl = "/assets/custom/draw/img/TU.png"
                }else if(v.stepTypeCode === 'procedure'){
                    imageUrl = "/assets/custom/draw/img/saveProcess.png"
                }
                var imgTemp = new joint.shapes.basic.Image({
                    "angle": 0,
                    "attrs" : {
                        "image": {"width": 40, "height": 40,'class':v.stepTypeCode,"stepId":v.stepId,'taskObjectId':v.taskObjectId,'xlink:href':imageUrl,'dxflowType':v.dxflowType},
                        "text": {"text": v.name,"ref-y": -5},
                    },
                    "id" : v.stepId,
                    "description": "image",
                    "position": {x: v.positionX?v.positionX:position+=200, y: v.positionY?v.positionY:600},
                    "size": {width: 40, height: 40},
                    "type": "basic.Image",
                    "z" : 1
                });
              
                arr.push(imgTemp)
            });

            $.each(result.object.linkList,function (i, v) {
                var linkObj = new joint.shapes.standard.Link({
                    "type" : 'standard.Link',
                    "z": 2,
                    id : v.linkId,
                    source : {id : v.fromStepId},
                    target: {id : v.endStepId},
                    //   connector: { name: 'rounded' },
                    smooth: true,
                    attrs: {
                        '.connection': {
                            stroke: '#20C1DD',
                            'stroke-width': 1.5,
                            pointerEvents: 'none',
                        },
                        '.marker-target': {
                            fill: '#20C1DD',
                            stroke: '#fff',
                            d: 'M 10 0 L 0 5 L 10 10 z'
                        }
                    },
                });
                arr.push(linkObj)
            });
            graph.addCell(arr);
            $(".tool-options").remove();
            paperScroller.centerContent();
        }
    },
    error : function (result) {
        console.log(result)
}
});

console.log($('.tab-pane.active', window.parent.document).attr('data-tuid'));

//点击需要加入的单元
$('.pullDown').on('click','a',function(){
    var url =base+ $(this).attr('data-addUrl');
    var name =base+ $(this).attr('name');
    console.log(url);
    var type = "";
    if($(this).hasClass('TU')){ 
    	type = "TU"
    }else if($(this).hasClass(' DXFLOW')){ 
    	type = "DXFLOW"
    }
    	$.ajax({
    	    url : base+'/rest/tuLayout/tuLicense?type='+type,
    	    type : 'GET',
    	    dataType: 'JSON',
    	    data :{tuId : tuid},
    	    success :function (result) {
    	    	if(result.code ==0 ){
    	    		parent.layer.open({
    	        	  	title:"选择"+name,
    	                type : 2,
    	                area : ['900px','500px'],
    	                content : url+"?tuId="+tuid,
    	                maxmin :true,
    	                btn : ['添加','关闭'],
    	                yes : function(index, layero){
    	                	var iframeWin = parent.window[layero.find('iframe')[0]['name']];

    	                    var json =iframeWin.getTableSelect();
    	                 

    	                 //   var obj = graph.toJSON();
    	              //      console.log(obj);
    	                    
    	                         var positionX = 500 + Math.random()*100;
    	                         var positionY = 600 + Math.random()*100;
    	                         var arr =[];
    	                         $.each(json,function(i,v){
    	                
    	                        	 var imageUrl;
    	                          
    	                             if (v.stepTypeCode === 'START'){
    	                                 imageUrl = "/assets/custom/draw/img/process_start.png";
    	                                 startId = v.stepId;
    	                             }else if (v.stepTypeCode === 'DXFLOW'){
    	                                 imageUrl = "/assets/custom/draw/img/DXFLOW.png"
    	                             }else {
    	                                 imageUrl = "/assets/custom/draw/img/TU.png"
    	                             }
    	                             var imgTemp = new joint.shapes.basic.Image({
    	                                 "angle": 0,
    	                                 "attrs" : {
    	                                     "image": {"width": 40, "height": 40,'class':v.stepTypeCode,"stepId":v.stepId,'taskObjectId':v.taskObjectId,'href':imageUrl,'dxflowType':v.dxflowType},
    	                                     "text": {"text": v.name,"ref-y":-5},
    	                                 },
    	                                 "id" : v.stepId,
    	                                 "description": "image",
    	                                 "position": {x: positionX+=200, y: positionY},
    	                                 "size": {width: 40, height: 40},
    	                                 "type": "basic.Image",
    	                                 "z" : 1
    	                             });
    	                             arr.push(imgTemp)
    	                           
    	                         });

    	                    graph.addCell(arr);
    	                    paperScroller.centerContent();
    	                    parent.layer.close(index)
    	                }
    	            });
    	    	}else{
    	    		layer.alert(result.msg);
    	    	}
    	    }
    	})
   
      
        /* }else if($(this).hasClass('TU')){
        layer.open({
            type : 2,
            area : ['900px','600px'],
            content : url,
          btn : ['添加','关闭'],
            yes : function(index, layero){
                var json = [

                    {
                        "taskObjectId":"b3e9d27f-ba45-4bb1-88dc-ae2c4d32af87",

                        "name":"seven",

                        "stepTypeCode":"TU",
                        "stepId" : uuid()
                    },

                    {
                        "taskObjectId":"4e389008-be91-4c0d-890e-cff0e53b9839",

                        "name":"kk",

                        "stepTypeCode":"TU",
                        "stepId" : uuid()

                    },

                    {
                        "taskObjectId":"a586407c-1418-4789-b31a-31fa4318c70c",

                        "name":"iiii",

                        "stepTypeCode":"TU",
                        "stepId" : uuid()
                    }

                ];
                var obj = graph.toJSON();

                var position = 500;
                $.each(json,function(i,v){
                    var imgTemp = {
                        "angle": 0,
                        "attrs" : {
                            "image": {"width": 60, "height": 60, "class": v.stepTypeCode,"stepId":v.stepId},
                            "text": {text: v.name},
                        },
                        "id" : v.taskObjectId,
                        "description": "image",
                        "position": {x: position+=300, y: 600},
                        "size": {width: 60, height: 60},
                        "type": "basic.Image",
                        "z" : 1
                    };
                   // imgTemp.attrs.image.href = (v.stepTypeCode == 'START')? ((v.stepTypeCode == 'DXFLOW')?"./img/DXFLOW.png":"./img/process_start.png"):"./img/TU.png";
                    if (v.stepTypeCode === 'START'){
                        imgTemp.attrs.image.href = "./img/process_start.png"
                    }else if (v.stepTypeCode === 'DXFLOW'){
                        imgTemp.attrs.image.href = "./img/DXFLOW.png"
                    }else {
                        imgTemp.attrs.image.href = "./img/TU.png"
                    }
                    obj.cells.push(imgTemp)
                });
                console.log(obj);

                graph.fromJSON(obj);
                paperScroller.centerContent();
                layer.close(index)
            }
        })
    }
*/
    $('.pullDown').addClass('display_none')
});

//点击加入
$('.addPBtn').click(function(){
    $('.pullDown').toggleClass('display_none')
});

//点击导出json
/*
$('#JSON').click(function(){
    console.log(graph.toJSON());
});
*/

//点击元素时的操作
paper.on('cell:pointerdown', function(cellView) {
	//console.log(cellView)
    // We don't want a Halo for links.
    if (cellView.model instanceof  joint.shapes.standard.Link) return;

    var halo = new joint.ui.Halo({theme: 'modern', cellView: cellView });

    var arr= graph.getLinks();

    halo.on('action:link:add', function(link) {
     //   console.log(graph.getLinks());
     //   console.log(link);

    $.each(arr,function (i,v) {
        //两个元素之间不能连多条线
        if (v.attributes.source.id !== null && v.attributes.source.id === link.attributes.source.id && v.attributes.target.id === link.attributes.target.id || v.attributes.source.id === link.attributes.target.id && v.attributes.target.id === link.attributes.source.id){
            link.remove();
        }

    });
        //元素和元素才能连线，元素不能连自己
        if (link.attributes.target.id === startId || !link.get('source').id || !link.get('target').id || link.get('source').id === link.get('target').id) {
            link.remove();
        }
        $(".tool-options").remove();
    });
    halo.removeHandle('clone');
    halo.removeHandle('fork');
    halo.removeHandle('unlink');
    halo.removeHandle('rotate');
    halo.removeHandle('resize');
    halo.changeHandle('remove', { position: 'ne' });
    halo.render();

   // console.log(cellView.model.attributes.attrs.image);
    if (cellView.model.attributes.attrs.image.class =='START'){
        $('.remove').remove();
    }
});

//双击元素
paper.on('cell:pointerdblclick',function(cellView){
    if(cellView.model.attributes.attrs.image.class === "TU"){
    	openTu(cellView);
    }else if(cellView.model.attributes.attrs.image.class === "DXFLOW"){
    	
    	openDXFLOW(cellView);
    }else if(cellView.model.attributes.attrs.image.class === "procedure"){
    	openProcedure(cellView);
    }
});

//右键点击元素
paper.on('cell:contextmenu',function(cellView,evt,x,y){

    if(cellView.model.attributes.type === "basic.Image" && cellView.model.attributes.attrs.image.class !== 'START'){
        var fa_item_ul = $('<ul class="vakata-context jstree-contextmenu jstree-default-contextmenu item_ul"></ul>');
        var  fa_item_li = ['打开','异常策略配置'];  //一级的li
        var e = evt || window.evt;

        $.each(fa_item_li,function (i, v) {
        	if(i === 0){
        		 fa_item_ul.append('<li class=""><a class="" href="#"><i class="iconfont icon-mimaxianshi"></i>'+v+'</a></li>');
        	}else if(i === 1){
        		 fa_item_ul.append('<li class=""><a class="" href="#"><i class="iconfont icon-yichang"></i>'+v+'</a></li>');
        	}
           
        });

        fa_item_ul.appendTo($('#app'));
        $('.item_ul').css({'display':'block','position':'absolute','z-index':'1000','background':'#fff','left':''+(e.clientX+10)+'px','top':''+(e.clientY+10)+'px'}).on('click','a',function(){
        	var type = $(this).text();
        	var stepId = cellView.model.id;
        	var taskObjectId = cellView.model.attributes.attrs.image.taskObjectId;
        	console.log( cellView.model);//stepTypeCode
        	//操作全部前端完成
        	if(type=="异常策略配置"){
        		$.ajax({
    				type:"GET",
    				url:"/rest/tuLayout/findExceStrategy",
    				data:{"stepId":stepId},
    				success:function(result){
    					if(result.code == 0){
    		        		layer.open({
    			                type : 2,
    			                content : ['/page/tuStep/tu/exceStrategy?stepId=' + stepId],
    			                area: ['700px', '300px'],
    			                maxmin : true,
    			                title : type,
    			                btn:['保存','取消'],
    			                yes: function(index, layero){			
    			                	//按钮【按钮一】的回调
    			                	var iframeWin = window[layero.find('iframe')[0]['name']];
    			                	var param = iframeWin.saveExceStrategy();
    			                	param.stepId = stepId;
    			                	param.taskObjectId =taskObjectId; 
    			                	var url ;
    			                	var stepType =  cellView.model.attributes.attrs.image.class;
    			                	if(stepType  =="DXFLOW"){
    			                		url =  "/rest/tuLayout/updateExceStrategy";
    			                	}else if(stepType == "TU"){
    			                		url = '/rest/tuLayout/fullExceStrategy';
    			                	}
    			                	$.ajax({
    			        				type:"GET",
    			        				url:url,
    			        				data:param,
    			        				success:function(data){
    			        					if(data.code == 0){
    			        						layer.close(index);	
    			        						layer.msg("保存成功");	
    			        					}else{
    			        						layer.msg(data.msg);	
    			        					}
    			        					
    			        				}
    			        			})
    			                	
    			                /*	cellView.model.attributes.attrs.image.maxRestartSize = param.maxRestartSize;
    			                	cellView.model.attributes.attrs.image.restartInterval = param.restartInterval;
    			                	cellView.model.attributes.attrs.image.isNextOnError = param.isNextOnError;*/
    			                		
    			                },
    			                btn2:function(index, layero){
    			                	layer.close(index);
    			                },
    			                success:function(layero,index){
    			                	var iframeWin = window[layero.find('iframe')[0]['name']];
    			                	var param = {};
    			                	param.maxRestartSize  =  result.object.maxRestartSize;
    			                	param.restartInterval = result.object.restartInterval;
    			                	param.isNextOnError = result.object.isNextOnError;
    			                	iframeWin.renderToPage(param);
    			                }
    		        		});
    					}else{
    						layer.alert(result.msg);
    					}
    				}
    			})
        		
        	}else if(type=="打开" && cellView.model.attributes.attrs.image.class === 'TU'){
        		openTu(cellView);
        	}
        	else if(type=="打开" && cellView.model.attributes.attrs.image.class === 'DXFLOW'){
        		openDXFLOW(cellView);
        	}else if(type=="打开" && cellView.model.attributes.attrs.image.class === 'procedure'){
        		openProcedure(cellView);
        	}
        });
      
    }


});

//右键删除列表
paper.on('blank:contextmenu',function(){
    $('.item_ul').remove()
});


//点击doucment删除列表
$(document).click(function(e){
    var tar = $(e.target);
    if(!tar.hasClass('erFisrtMenu')){
        $('.item_ul').remove()
    }
});

//元素间的对齐线
var snaplines = new joint.ui.Snaplines({ paper: paper });
snaplines.startListening();


//鹰眼开始
var nav = new joint.ui.Navigator({
    paperScroller: paperScroller,
    width: 133,
    height: 100,
    padding: 5,
    model: graph,
    gridSize: 1,
//        zoomOptions: { max: 2, min: 0.12 }
});
nav.$el.appendTo('#myholder-small');
nav.render();
//小图结束

//tooltip模块
new joint.ui.Tooltip({
    target: '[data-tooltip]',
    rootTarget: document.body,
    direction: 'auto',
    padding: 15,
});


//打开TU
function openTu(cellView){
	var name = cellView.model.attributes.attrs.text.text;
    var url =  '/page/tuStep/processSet';
    var this_id = cellView.model.attributes.attrs.image.taskObjectId +'_anchor';
    parent.addTab(name,url,this_id);
}

//打开DXFLOW
function openDXFLOW(cellView){
	var dxFlowId = cellView.model.attributes.attrs.image.taskObjectId ;
	var dxflowType = cellView.model.attributes.attrs.image.dxflowType ;
	if(dxflowType == null  ||  dxflowType  == 'null'){
		dxflowType = '';
	}
	parent.layer.open({
        type : 2,
        content : [base + '/page/process/design/modify?dxFlowId='+dxFlowId+'&type='+dxflowType],
        area: ['900px', '500px'],
        maxmin : true,
        title : '修改流程'
    });
}

//打开procedure
function openProcedure(cellView){
	var stepId = cellView.model.id;
    var taskObjectId = cellView.model.attributes.attrs.image.taskObjectId;
    var stepType =  cellView.model.attributes.attrs.image.class;
    parent.layer.open({
        title : '存储过程',
        type : 2,
	        area : ['900px' , '500px'],
        maxmin : true,
        content: ['/page/tuStep/tu/storedProcedure?taskObjectId='+taskObjectId],
        btn:["确定","取消"],
        yes:function(index, layero){
        	var taskObjectId = cellView.model.attributes.attrs.image.taskObjectId;
        	var iframeWin = parent.window[layero.find('iframe')[0]['name']];
        	var tuId = $('.tab-pane.active', window.parent.document).attr('data-tuid');
        	var isSubmit  = iframeWin.formValid();
        	if(isSubmit){
        		var  procedure = iframeWin.getData();
        			 procedure.stepId = stepId;
        		 $.ajax({
    		         async: false,
    		         type: "POST",
    		         url:"/rest/tuLayout/saveProcedure",
    		         data:{tuId:tuId, stepName:procedure.stepName,stepId:stepId,taskObjectId:taskObjectId, data:JSON.stringify(procedure)},
    		         success:function(result){
    		        	 if(result.code == 0){
    		        		var map =  result.object;
    		        		if(cellView.model.attributes.attrs.image.taskObjectId == null){
    		        			cellView.model.attributes.attrs.image.stepId = uuid();
    		        			cellView.model.attributes.attrs.image.taskObjectId = map.taskObjectId;
    		        		}
    		        		cellView.$el.find("text").text(procedure.stepName)
    		        		cellView.model.attributes.attrs.text.text = procedure.stepName
    		        		parent.layer.alert("保存成功");
    		        	 }else{
    		        		 parent.layer.alert(result.msg);
    		        	 }
    		         }
    		  })
        	}
        },
        btn2:function(index, layero){
        	layer.close(index);
        }
    })
}

//生成uuid方法
function uuid() {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";

    var uuid = s.join("");
    return uuid;
}